<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能对话助手</title>
    <!-- 引入依赖 -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/marked.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #f5f5f5;
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: #fff;
            padding: 16px;
            border-bottom: 1px solid #e0e0e0;
            text-align: center;
            font-size: 20px;
            font-weight: 600;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            max-width: 1200px;
            width: 100%;
            margin: 0 auto;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
        }

        .user-message {
            justify-content: flex-end;
        }

        .assistant-message {
            justify-content: flex-start;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 8px;
            line-height: 1.6;
        }

        .user-message .message-content {
            background: #1a73e8;
            color: white;
        }

        .assistant-message .message-content {
            background: white;
            border: 1px solid #e0e0e0;
        }

        .input-area {
            background: white;
            padding: 20px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
            max-width: 1200px;
            width: 100%;
            margin: 0 auto;
        }

        #input-box {
            flex: 1;
            padding: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            resize: none;
            min-height: 44px;
            max-height: 200px;
        }

        button {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            background: #1a73e8;
            color: white;
            cursor: pointer;
            transition: opacity 0.2s;
        }

        button:hover {
            opacity: 0.9;
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        /* Markdown内容样式 */
        .message-content code {
            background: rgba(175, 184, 193, 0.2);
            padding: 2px 4px;
            border-radius: 4px;
            font-family: monospace;
        }

        .message-content pre {
            background: #f6f8fa;
            padding: 16px;
            border-radius: 6px;
            overflow-x: auto;
        }

        .message-content pre code {
            background: none;
            padding: 0;
        }

        /* 新增加载状态样式 */
        .loading {
            color: #666;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="header">智能对话助手</div>
    
    <div class="chat-container" id="chat-box">
        <!-- 对话消息将动态插入到这里 -->
    </div>

    <div class="input-area">
        <textarea id="input-box" placeholder="输入您的问题..." rows="1"></textarea>
        <button id="send-btn">发送</button>
        <button id="clear-btn">清空</button>
    </div>

    <script>
        $(document).ready(function() {
            const $chatBox = $('#chat-box');
            const $input = $('#input-box');
            const $sendBtn = $('#send-btn');
            let currentEventSource = null;

            // 流式消息处理器
            class StreamHandler {
                constructor() {
                    this.buffer = [];
                    this.$messageElement = null;
                    this.markdownBuffer = '';
                }

                initStream() {
                    this.buffer = [];
                    this.markdownBuffer = '';
                    this.$messageElement = addMessage('<div class="loading">思考中...</div>', false);
                    this.lastUpdate = Date.now();
                }

                appendData(data) {
                    this.buffer.push(data);
                    this.markdownBuffer += data;

                    // 节流更新（每秒最多更新15次）
                    if (Date.now() - this.lastUpdate > 66) {
                        this.updateDisplay();
                        this.lastUpdate = Date.now();
                    }
                }

                updateDisplay() {
                    const rawContent = this.buffer.join('');
                    const parsedContent = marked.parse(this.markdownBuffer);

                    this.$messageElement.find('.message-content').html(parsedContent);
                    $chatBox.scrollTop($chatBox[0].scrollHeight);
                }

                completeStream() {
                    this.updateDisplay();
                    this.$messageElement.find('.loading').remove();
                    this.cleanup();
                }

                cleanup() {
                    this.buffer = null;
                    this.$messageElement = null;
                    this.markdownBuffer = '';
                }
            }

            // 发送消息处理（改造为EventSource）
            $sendBtn.click(function() {
                const content = $input.val().trim();
                if (!content || currentEventSource) return;

                addMessage(content, true);
                $input.val('');
                adjustHeight();

                const streamHandler = new StreamHandler();
                streamHandler.initStream();

                currentEventSource = new EventSource(
                    `http://localhost:8080/ai/streamChat?input=${encodeURIComponent(content)}`
                );

                currentEventSource.onmessage = (event) => {
                    if (event.data === '[DONE]') {
                        currentEventSource.close();
                        streamHandler.completeStream();
                        currentEventSource = null;
                        $sendBtn.prop('disabled', false);
                    } else {
                        streamHandler.appendData(event.data);
                    }
                };

                currentEventSource.onerror = (error) => {
                    console.error('SSE Error:', error);
                    streamHandler.$messageElement.find('.message-content')
                        .html('连接中断，请重试');
                    currentEventSource.close();
                    currentEventSource = null;
                    $sendBtn.prop('disabled', false);
                };

                $sendBtn.prop('disabled', true);
            });

            // 清空时关闭现有连接
            $('#clear-btn').click(function() {
                if (currentEventSource) {
                    currentEventSource.close();
                    currentEventSource = null;
                }
                $chatBox.empty();
            });


            // 自动调整输入框高度
            function adjustHeight() {
                $input.height('auto').height($input[0].scrollHeight);
            }
            $input.on('input', adjustHeight);


            // 添加消息到对话界面
            function addMessage(content, isUser) {
                const messageClass = isUser ? 'user-message' : 'assistant-message';
                const contentHtml = isUser ? content : marked.parse(content);
                
                const messageHtml = `
                    <div class="message ${messageClass}">
                        <div class="message-content">${contentHtml}</div>
                    </div>
                `;
                
                const $message = $(messageHtml);
                $chatBox.append($message);
                $chatBox.scrollTop($chatBox[0].scrollHeight);
                return $message; // 返回消息元素便于后续更新
            }

            // 回车发送（Shift+Enter换行）
            $input.keydown(function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    $sendBtn.click();
                }
            });
        });
    </script>
</body>
</html>